// http.ts
import axios from 'axios'

// 定义配置类型（不再直接从 axios 导入类型）
interface RequestConfig {
    no_cache?: boolean;
    headers?: Record<string, string>;
    params?: Record<string, any>;
    data?: any;
    cancelToken?: any; // 使用 any 避免类型问题
    [key: string]: any; // 其他 axios 配置
}

// 创建实例
const http = axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
    timeout: 10000,
})

// 请求拦截器
http.interceptors.request.use((config: RequestConfig) => {
    const token = localStorage.getItem('yiguo_token')
    const lang = localStorage.getItem('lang') || 'zh-CN'

    config.headers = {
        ...config.headers,
        Authorization: token ? `${token}` : undefined,
        'x-lang': lang || undefined,
    }

    if (!config.no_cache) {
        config.params = {
            ...config.params,
            _: Date.now(),
        }
    }

    return config
})

// 响应拦截器
http.interceptors.response.use(
    (response) => response.data,
    (error) => {
        if (axios.isCancel(error)) {
            console.log('Request canceled:', error.message)
        } else if (error.response) {
            console.error('HTTP error:', error.response.status)
        } else {
            console.error('Network error:', error.message)
        }
        return Promise.reject(error)
    },
)

// 取消请求工具
export const createCancelToken = () => {
    const source = axios.CancelToken.source()
    return {
        cancel: (message?: string) => source.cancel(message || 'Request canceled'),
        token: source.token,
    }
}

// 请求方法
export const $get = <T>(url: string, config?: RequestConfig) =>
    http.get<T>(url, config)

export const $post = <T>(url: string, data?: any, config?: RequestConfig) =>
    http.post<T>(url, data, config)

export const $put = <T>(url: string, data?: any, config?: RequestConfig) =>
    http.put<T>(url, data, config)

export const $del = <T>(url: string, config?: RequestConfig) =>
    http.delete<T>(url, config)

export default http